package com.zhoug.common3.utils;

import android.os.Handler;
import android.os.Looper;

/**
 * 计时器
 *
 * @Author: zhoug
 * @Date: 2024-09-05
 * @Description:
 */
public class TimeCounter {
    private static boolean debug = true;
    private static final String TAG = ">>>TimeCounter";
    private static final int DEF_DURING_TIME = 1000;

    /**
     * 间隔多长时间执行1次,单位毫秒
     */
    private int duringTime = DEF_DURING_TIME;
    /**
     * 数据递增
     */
    public static final int TYPE_ADD = 0;
    /**
     * 数据递减
     */
    public static final int TYPE_MINUS = 1;
    /**
     * {@link #TYPE_ADD,#TYPE_MINUS}
     */
    private int type = TYPE_ADD;
    /**
     * 每次的增量
     */
    private int increment = 1;
    /**
     * 结束数据
     */
    private int endValue = Integer.MAX_VALUE;
    /**
     * 开始数据
     */
    private int startValue = 0;
    /**
     * 当前数据
     */
    private int value = 0;


    private OnTimeListener mOnTimeListener;
    private final Handler mHandler = new Handler(Looper.getMainLooper());

    private final Runnable mDateRunnable = new Runnable() {
        @Override
        public void run() {
            if (mOnTimeListener != null) {
                mOnTimeListener.onTimeChange(value);
            }
            if (type == TYPE_ADD) {
                value+=increment;
                if (value <= endValue) {
                    mHandler.postDelayed(mDateRunnable, duringTime);
                }
            } else {
                value-=increment;
                if (value >= endValue) {
                    mHandler.postDelayed(mDateRunnable, duringTime);
                }
            }
        }
    };

    /**
     * 开启
     */
    public synchronized void start() {
        if (debug) {
            LogUtils.d(TAG, "start:");
        }
        mHandler.removeCallbacks(mDateRunnable);
        mHandler.post(mDateRunnable);
    }

    /**
     * 停止
     */
    public synchronized void stop() {
        if (debug) {
            LogUtils.d(TAG, "stop:");
        }
        mHandler.removeCallbacks(mDateRunnable);
    }


    public void setDuringTime(int duringTime) {
        this.duringTime = duringTime;
    }

    public void setType(int type) {
        this.type = type;
    }

    public void setIncrement(int increment) {
        this.increment = increment;
    }

    public void setEndValue(int endValue) {
        this.endValue = endValue;
    }

    public void setStartValue(int startValue) {
        this.startValue = startValue;
        this.value = startValue;
    }

    public void resetValue(){
        this.value=this.startValue;
    }

    public void setOnTimeListener(OnTimeListener onTimeListener) {
        this.mOnTimeListener = onTimeListener;
    }

    public interface OnTimeListener {
        void onTimeChange(int value);
    }
}
